import React, { useMemo, useState, useEffect, useRef } from 'react';
import { 
  Card, 
  Spin, 
  Typography, 
  Button,
  Space,
  Alert,
  message,
  Progress,
  Divider,
  Tag
} from 'antd';
import {
  ExperimentOutlined,
  PlayCircleOutlined,
  InfoCircleOutlined,
  CheckOutlined,
  RobotOutlined,
  LoadingOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import { useAnalysisContext, useAnalysisActions } from '../../context/AnalysisContext';
import EnhancedProblemTable from './EnhancedProblemTable';
import { UnifiedProblemData, AnalysisSource } from '../../types/analysis';
import { convertLegacyProblemsToUnified, generateMockAIProblems } from '../../utils/problemDataConverter';
import './AnalysisResults.css';

const { Text } = Typography;

// 批处理进度信息接口
interface BatchProgress {
  type: string;
  percentage: number;
  message: string;
  currentBatch?: number;
  totalBatches?: number;
  processedStatements?: number;
  totalStatements?: number;
}

// 完成事件接口
interface CompletedEvent {
  result: any;
  message: string;
}

// 错误事件接口
interface ErrorEvent {
  error: string;
}

const EnhancedUnifiedAiAnalysisResults: React.FC = () => {
  const { state } = useAnalysisContext();
  const actions = useAnalysisActions();
  const [mockAIEnabled, setMockAIEnabled] = useState(true);
  
  // 批处理相关状态
  const [batchProgress, setBatchProgress] = useState<BatchProgress | null>(null);
  const [analysisStartTime, setAnalysisStartTime] = useState<number | null>(null);
  const [elapsedTime, setElapsedTime] = useState<number>(0);
  const eventSourceRef = useRef<EventSource | null>(null);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  const {
    analysisResult,
    isAnalyzing,
    sqlContent,
    sourceDbType,
    targetDbType,
    selectedIssueId
  } = state;

  // 时间计时器效果
  useEffect(() => {
    if (isAnalyzing && analysisStartTime) {
      timerRef.current = setInterval(() => {
        setElapsedTime(Date.now() - analysisStartTime);
      }, 1000);
    } else {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    }

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, [isAnalyzing, analysisStartTime]);

  // 清理EventSource
  useEffect(() => {
    return () => {
      if (eventSourceRef.current) {
        eventSourceRef.current.close();
        eventSourceRef.current = null;
      }
    };
  }, []);

  // 启动批处理分析
  const startBatchAnalysis = async () => {
    if (!sqlContent.trim()) {
      message.error('请输入SQL内容');
      return;
    }

    // 设置分析状态
    actions.setIsAnalyzing(true);
    actions.clearAnalysisResult();
    setBatchProgress(null);
    setAnalysisStartTime(Date.now());
    setElapsedTime(0);

    // 关闭现有的连接
    if (eventSourceRef.current) {
      eventSourceRef.current.close();
    }

    try {
      // 准备请求数据
      const requestData = {
        sqlContent,
        sourceDbType,
        targetDbType,
        userId: state.userId
      };

      // 发送POST请求启动分析
      const response = await fetch('/api/ai-analysis/analyze-with-progress', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestData)
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      // 创建EventSource连接
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法获取响应流');
      }

      const decoder = new TextDecoder();
      let buffer = '';

      while (true) {
        const { done, value } = await reader.read();
        
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        
        // 处理服务器发送事件
        const events = buffer.split('\n\n');
        buffer = events.pop() || '';

        for (const event of events) {
          if (!event.trim()) continue;

          try {
            // 解析SSE格式
            const lines = event.split('\n');
            let eventName = '';
            let eventData = '';

            for (const line of lines) {
              if (line.startsWith('event:')) {
                eventName = line.substring(6).trim();
              } else if (line.startsWith('data:')) {
                eventData += line.substring(5).trim();
              }
            }

            if (eventData) {
              const data = JSON.parse(eventData);
              
              if (eventName === 'progress') {
                setBatchProgress(data as BatchProgress);
              } else if (eventName === 'completed') {
                const completedData = data as CompletedEvent;
                actions.setAnalysisResult(completedData.result);
                actions.setIsAnalyzing(false);
                setBatchProgress(null);
                message.success('AI分析完成');
                break;
              } else if (eventName === 'error') {
                const errorData = data as ErrorEvent;
                message.error(`分析失败: ${errorData.error}`);
                actions.setIsAnalyzing(false);
                setBatchProgress(null);
                break;
              }
            }
          } catch (parseError) {
            console.warn('解析事件数据失败:', parseError);
          }
        }
      }

    } catch (error) {
      console.error('批处理分析失败:', error);
      message.error(`分析失败: ${error instanceof Error ? error.message : '未知错误'}`);
      actions.setIsAnalyzing(false);
      setBatchProgress(null);
    }
  };

  // 生成统一的问题数据
  const unifiedProblems = useMemo((): UnifiedProblemData[] => {
    let problems: UnifiedProblemData[] = [];

    // 如果有真实的分析结果，使用真实数据
    if (analysisResult?.issues) {
      problems = analysisResult.issues.map((issue: any, issueIndex: number) => ({
        id: `issue-${issueIndex}`,
        statementNumber: issue.statementNumber || 1,
        lineNumber: issue.lineNumber || 1,
        columnNumber: issue.columnNumber || 1,
        severity: issue.severity || 'MEDIUM',
        category: issue.category || 'COMPATIBILITY',
        description: issue.description || '',
        suggestion: issue.suggestion || '',
        ruleName: issue.ruleName || 'AI_ANALYSIS',
        issueType: issue.issueType || 'COMPATIBILITY',
        sqlContent: issue.sqlContent || '',
        originalCode: issue.originalCode || '',
        suggestedCode: issue.suggestedCode || '',
        sqlFragment: issue.sqlFragment || '',
        analysisSource: 'LLM' as AnalysisSource,
        confidence: issue.confidence || 85,
        aiGenerated: true
      })) || [];
    } else if (mockAIEnabled && sqlContent.trim() && !isAnalyzing) {
      // 临时：模拟数据
      problems = generateMockAIProblems(sqlContent);
    }

    return problems;
  }, [analysisResult, sqlContent, mockAIEnabled, isAnalyzing]);

  // 计算统计数据
  const statistics = useMemo(() => {
    return {
      total: unifiedProblems.length,
      high: unifiedProblems.filter(p => p.severity === 'HIGH').length,
      medium: unifiedProblems.filter(p => p.severity === 'MEDIUM').length,
      low: unifiedProblems.filter(p => p.severity === 'LOW').length,
      info: unifiedProblems.filter(p => p.severity === 'INFO').length,
      avgConfidence: unifiedProblems.length > 0 
        ? Math.round(unifiedProblems.reduce((sum, p) => sum + (p.confidence || 0), 0) / unifiedProblems.length)
        : 0
    };
  }, [unifiedProblems]);

  // 格式化时间
  const formatTime = (ms: number): string => {
    const seconds = Math.floor(ms / 1000);
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return minutes > 0 ? `${minutes}分${remainingSeconds}秒` : `${remainingSeconds}秒`;
  };

  // 处理问题点击
  const handleIssueClick = (issue: UnifiedProblemData) => {
    actions.setSelectedIssueId(issue.id);
    actions.setCursorPosition({ 
      line: issue.lineNumber, 
      column: issue.columnNumber 
    });
  };

  // 处理应用建议
  const handleApplySuggestion = (issue: UnifiedProblemData) => {
    if (!issue.suggestedCode) {
      message.warning('该问题没有优化建议');
      return;
    }

    const newSqlContent = sqlContent.replace(
      issue.originalCode || issue.sqlFragment || '',
      issue.suggestedCode
    );
    
    actions.setSqlContent(newSqlContent);
    message.success(`已应用SQL#${issue.statementNumber}的优化建议`);
  };

  // 处理批量应用
  const handleBatchApply = (issues: UnifiedProblemData[]) => {
    let newSqlContent = sqlContent;
    
    const sortedIssues = [...issues].sort((a, b) => a.statementNumber - b.statementNumber);
    
    sortedIssues.forEach(issue => {
      if (issue.suggestedCode && (issue.originalCode || issue.sqlFragment)) {
        newSqlContent = newSqlContent.replace(
          issue.originalCode || issue.sqlFragment || '',
          issue.suggestedCode
        );
      }
    });
    
    actions.setSqlContent(newSqlContent);
    message.success(`已批量应用 ${issues.length} 个优化建议`);
  };

  // 渲染批处理进度
  const renderBatchProgress = () => {
    if (!isAnalyzing || !batchProgress) {
      return null;
    }

    return (
      <div style={{ marginBottom: 16 }}>
        <Space direction="vertical" style={{ width: '100%' }} size="small">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Text strong>{batchProgress.message}</Text>
            <Space>
              {batchProgress.totalBatches && (
                <Tag color="blue">
                  {batchProgress.currentBatch || 0}/{batchProgress.totalBatches} 批次
                </Tag>
              )}
              <Tag icon={<ClockCircleOutlined />} color="green">
                {formatTime(elapsedTime)}
              </Tag>
            </Space>
          </div>
          
          <Progress 
            percent={Math.round(batchProgress.percentage)}
            status={batchProgress.percentage === 100 ? 'success' : 'active'}
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
          />
          
          {batchProgress.totalStatements && (
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', color: '#666' }}>
              <span>已处理语句: {batchProgress.processedStatements || 0}</span>
              <span>总语句数: {batchProgress.totalStatements}</span>
            </div>
          )}
        </Space>
      </div>
    );
  };

  // 渲染空状态
  const renderEmptyState = () => {
    if (!sqlContent.trim()) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <ExperimentOutlined />
          </div>
          <div className="analysis-empty-text">
            请在左侧编辑器中输入SQL语句
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            AI将智能分析您的SQL并提供优化建议，支持批量处理大规模SQL
          </Text>
        </div>
      );
    }

    if (sourceDbType === targetDbType) {
      return (
        <div className="analysis-empty">
          <div className="analysis-empty-icon">
            <InfoCircleOutlined />
          </div>
          <div className="analysis-empty-text">
            源数据库和目标数据库相同
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            请选择不同的数据库类型进行AI分析
          </Text>
        </div>
      );
    }

    return (
      <div className="analysis-empty">
        <div className="analysis-empty-icon">
          <PlayCircleOutlined />
        </div>
        <div className="analysis-empty-text">
          点击"开始AI分析"按钮进行智能分析
        </div>
        <Text type="secondary" style={{ fontSize: '12px' }}>
          支持批量处理，自动优化大规模SQL数据集
        </Text>
        <div style={{ marginTop: 16 }}>
          <Button 
            type="primary" 
            icon={<RobotOutlined />}
            onClick={startBatchAnalysis}
            loading={isAnalyzing}
          >
            开始AI分析
          </Button>
        </div>
      </div>
    );
  };

  // 渲染成功状态
  const renderSuccessState = () => (
    <div className="analysis-empty">
      <div className="analysis-empty-icon" style={{ color: '#52c41a' }}>
        <CheckOutlined />
      </div>
      <div className="analysis-empty-text">
        AI分析完成，未发现兼容性问题
      </div>
      <Text type="secondary" style={{ fontSize: '12px' }}>
        您的SQL语句在目标数据库中兼容性良好
      </Text>
    </div>
  );

  return (
    <Card 
      className="results-section ai-analysis-results"
      title={
        <Space>
          <RobotOutlined />
          <span>AI智能分析</span>
          {isAnalyzing && <LoadingOutlined spin />}
          {statistics.avgConfidence > 0 && (
            <Tag color="blue">
              置信度: {statistics.avgConfidence}%
            </Tag>
          )}
        </Space>
      }
      size="small"
      extra={
        <Space>
          {!isAnalyzing && sqlContent.trim() && (
            <Button 
              size="small" 
              type="primary"
              icon={<RobotOutlined />}
              onClick={startBatchAnalysis}
            >
              重新分析
            </Button>
          )}
          {mockAIEnabled && (
            <Button 
              size="small" 
              type="link"
              onClick={() => setMockAIEnabled(!mockAIEnabled)}
            >
              {mockAIEnabled ? '关闭模拟' : '启用模拟'}
            </Button>
          )}
        </Space>
      }
    >
      {isAnalyzing ? (
        <div className="analysis-loading">
          {renderBatchProgress()}
          {!batchProgress && (
            <div style={{ textAlign: 'center' }}>
              <Spin size="large" />
              <div style={{ marginTop: 16 }}>
                <Text>AI正在分析您的SQL...</Text>
                <br />
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  {elapsedTime > 0 && `已运行 ${formatTime(elapsedTime)} • `}
                  分析大量SQL时会自动分批处理
                </Text>
              </div>
            </div>
          )}
        </div>
      ) : unifiedProblems.length > 0 ? (
        <div>
          {statistics.total > 0 && (
            <Alert
              message={`AI识别到 ${statistics.total} 个潜在问题`}
              description={
                <div>
                  <span>高危: {statistics.high}个, 中危: {statistics.medium}个, 低危: {statistics.low}个</span>
                  {statistics.avgConfidence > 0 && (
                    <span style={{ marginLeft: 16 }}>
                      平均置信度: {statistics.avgConfidence}%
                    </span>
                  )}
                </div>
              }
              type={statistics.high > 0 ? 'error' : statistics.medium > 0 ? 'warning' : 'info'}
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}
          
          <EnhancedProblemTable
            problems={unifiedProblems}
            selectedIssueId={selectedIssueId}
            onIssueClick={handleIssueClick}
            onApplySuggestion={handleApplySuggestion}
            onBatchApply={handleBatchApply}
            height={600}
            taskConfig={{ taskType: 'MANUAL_SQL' }} // 手动SQL分析默认配置
          />
        </div>
      ) : (
        analysisResult ? renderSuccessState() : renderEmptyState()
      )}
    </Card>
  );
};

export default EnhancedUnifiedAiAnalysisResults;